package com.admgt.resource.ui;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.tree.TreePath;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import com.admgt.resource.entity.LoadingInfo;
import com.admgt.resource.service.FtpUsernameOrPwdException;
import com.admgt.resource.service.ResourceService;
/**
 * Act as a controller between resourceFrame and resourceService
 * @author James
 *
 */
public class ResourceContext {
	private ResourceService resourceService;
	private ResourceFrame resourceFrame;

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public void setResourceFrame(ResourceFrame resourceFrame) {
		this.resourceFrame = resourceFrame;
	}
	
	public FTPClient getFtpClient() {
		return resourceService.getFtpClient();
	}

	/**
	 * connect to FTP server and return the connected Ftp instance, 
	 * otherwise throw out the exception
	 */
	public void connectFtpServer() {
		try {
			String hostname= resourceFrame.getHostName();
			int port =resourceFrame.getPort()==0?21:resourceFrame.getPort();
			String username = resourceFrame .getUserName();
			String password = resourceFrame.getPassword();
			resourceService.connectFtpServer(hostname, port, username, password);
		}catch(NumberFormatException e){//当应用程序试图将字符串转换成一种数值类型，但该字符串不能转换为适当格式时，抛出该异常。
		      e.printStackTrace();
		      JOptionPane.showMessageDialog(
		    		  resourceFrame, "端口号必须是数字!");
		}catch(FtpUsernameOrPwdException e){
		      e.printStackTrace();
		      //loginFrame.showError("登录失败");
		      JOptionPane.showMessageDialog(
		    		  resourceFrame, "FTP服务器连接失败！");
		}catch(Exception e){
		      e.printStackTrace();
		      JOptionPane.showMessageDialog(
		    		  resourceFrame, e.getMessage());
		}
	}
	
	public void download(){
		try {
			
			String localPath = resourceFrame.getLocalPath();
			String ftpServerFileName = resourceFrame.getFtpServerFileName();
			
			if(localPath!=null &&
					ftpServerFileName!=null){
				resourceService.download(ftpServerFileName, localPath);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(
		    		  resourceFrame, e.getMessage());
		}
	}
	

	public Object[] addRowData() {
		Object[] rowData =null;
		try {
			
			String localPath = resourceFrame.getLocalPath();
			String ftpServerFileName = resourceFrame.getFtpServerFileName();
			
			if(localPath!=null &&
					ftpServerFileName!=null){
				rowData = resourceService.addLoadingInfo(ftpServerFileName, localPath);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(
		    		  resourceFrame, e.getMessage());
		}
		return rowData;
	}
	
	public void upload(){
		try {
			TreePath[] localPaths = resourceFrame.getPaths();
			for(TreePath treePath :localPaths ){
				Object[] filePath = treePath.getPath();
				int length = filePath.length;
				String ftpServerFileName = filePath[length-1].toString();
				String localPath = "";
				for(int i=0;i<length;i++){
					localPath += filePath[i]+"/";
				}
				System.out.println("localPath="+localPath);
				localPath = localPath.substring(localPath.indexOf("C:\\"), localPath.length()-1);
				System.out.println("localPath="+localPath);
				resourceService.upload(localPath, ftpServerFileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(
		    		  resourceFrame, e.getMessage());
		}
	}
	/**
	 * display the window
	 */
	public void show(){
	    center(resourceFrame);
	    resourceFrame.setVisible(true);
	}

	/**
	 *  窗口居中显示
	 * @param win
	 */
	public void center(Container win) {
		Toolkit toolkit = Toolkit.getDefaultToolkit();// 获取系统默认工具包
		Dimension screen = toolkit.getScreenSize();// dimension尺寸,public abstract Dimension getScreenSize()
		int x = (screen.width - win.getWidth()) / 2;
		int y = (screen.height - win.getHeight()) / 2;
		win.setLocation(x, y);
	}
	/**
	 * 关闭当前窗口
	 * @param frame
	 */
	public void exit(JFrame frame) {
		int val = JOptionPane.showConfirmDialog(frame, "要退出系统吗?");
		if (val == JOptionPane.YES_OPTION) {
			frame.setVisible(false);
			System.exit(0);// 结束所有系统进程(终止当前正在运行的java虚拟机）
		}
	}


	public Object[][] getTableData() {
		Object tableData[][] = null;
		FTPClient ftpClient = resourceService.getFtpClient();
		try {
			if (ftpClient.isConnected()) {
				FTPFile[] files = ftpClient.listFiles();
				int n = files.length;
				tableData = new Object[n][6];
				for (int i = 0; i < n; i++) {
					System.out.println(files[i].getRawListing());
					tableData[i][0] = files[i].getName();
					tableData[i][1] = files[i].getSize();
					tableData[i][2] = files[i].isDirectory() ? "文件夹" : "文件";
					tableData[i][3] = files[i].getTimestamp().getTime();
					tableData[i][4] = files[i].getRawListing().substring(0, 9);
					tableData[i][5] = i + 1;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(resourceFrame, e.getMessage());
		}

		return tableData;
	}

	public int updateProgress(int id,String ftpServerFileName,String localPath) {
		int progress=0;
		try {
			if(localPath!=null &&
					ftpServerFileName!=null){
				progress = resourceService.updateProgress(id, ftpServerFileName, localPath);
			}
				
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(
		    		  resourceFrame, e.getMessage());
		}
		return progress;
	}



}
